from django.shortcuts import render, redirect  
from .models import Image  
from .forms import ImageUploadForm  

from rest_framework import generics
from rest_framework import filters
from rest_framework import status
from rest_framework import viewsets
from rest_framework.response import Response  
from rest_framework.views import APIView
from rest_framework.filters import OrderingFilter
from .models import Submission, RelatedForm, Message
from .serializers import SubmissionSerializer,RelatedFormSerializer , MessageSerializer

from django_filters.rest_framework import DjangoFilterBackend, FilterSet
import django_filters
from django.shortcuts import get_object_or_404

from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import AllowAny
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User  # 注意：这里应该是你的CustomUser模型
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError
from django.views.decorators.csrf import csrf_exempt
  
def upload_image(request):  
    if request.method == 'POST':  
        form = ImageUploadForm(request.POST, request.FILES)  
        if form.is_valid():  
            form.save()  
            return redirect('image_list')  
    else:  
        form = ImageUploadForm()  
    return render(request, 'upload_image.html', {'form': form})  
  
def image_list(request):  
    images = Image.objects.all()  
    return render(request, 'image_list.html', {'images': images})
	  
class SubmissionViewSet(generics.CreateAPIView):  
    queryset = Submission.objects.all()  
    serializer_class = SubmissionSerializer
    
    def create(self, request, *args, **kwargs):  
        # 序列化并验证提交的数据  
        submission_serializer = self.serializer_class(data=request.data)  
        submission_serializer.is_valid(raise_exception=True)  
        submission = submission_serializer.save()  

        # 创建 RelatedForm 实例  
        related_data = {  
            'progress_description': '问题提交',  
            'progress': '问题提交',  # 可以从请求数据中获取进度，或者设置默认值  
            'original_form': submission.id  # 使用保存后的 Submission 实例  
        }  
        related_serializer = RelatedFormSerializer(data=related_data)  
        related_serializer.is_valid(raise_exception=True)  
        #related_form = related_serializer.save()  

        # 返回响应，可能包含新创建的对象的表示  
        return Response({  
            'submission': submission_serializer.data,  
            'related_form': related_serializer.data  
        }, status=status.HTTP_201_CREATED)
	
class FormSubmissionListView(generics.ListAPIView):  
    queryset = Submission.objects.all()  
    serializer_class = SubmissionSerializer  
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]  
    filterset_fields = ['location', 'issue', 'type']  # 可过滤的字段  
    ordering_fields = ['timestamp', 'location']  # 可排序的字段
 
class FormSubmissionDetailView(generics.RetrieveAPIView):  
    queryset = Submission.objects.all()  
    serializer_class = SubmissionSerializer  
    lookup_field = 'id'  # 假设使用ID作为唯一标识符
	
	
class RelatedFormUpdateView(APIView):  
    def put(self, request, original_form_id, *args, **kwargs):  
        try:  
            original_form = OriginalForm.objects.get(id=original_form_id)  
        except OriginalForm.DoesNotExist:  
            return Response(status=status.HTTP_404_NOT_FOUND)  
 
        related_form, created = RelatedForm.objects.get_or_create(original_form=original_form)  
        related_serializer = RelatedFormSerializer(related_form, data=request.data, partial=True)  
        related_serializer.is_valid(raise_exception=True)  
        related_serializer.save()  
 
        return Response(related_serializer.data, status=status.HTTP_200_OK)
		
		
class RelatedFormFilter(FilterSet):  
    original_form_id = django_filters.NumberFilter(name='original_form', lookup_expr='exact')  
  
    class Meta:  
        model = RelatedForm  
        fields = ['original_form_id']  
  
class RelatedFormDetailByOriginalForm(generics.RetrieveAPIView):
    queryset = RelatedForm.objects.all()
    serializer_class = RelatedFormSerializer
 
    def get_object(self):
        original_form_id = self.kwargs.get('original_form_id')
        original_form = get_object_or_404(RelatedForm, id=original_form_id)
        related_form = self.queryset.filter(original_form=original_form).first()
        if related_form is None:
            raise Http404
        return related_form
		
from django.db.models import Q		
from rest_framework.permissions import IsAuthenticated
from .models import CustomUser, Task, SubTask, AttachedTask
from .serializers import CustomUserSerializer, TaskSerializer, SubTaskSerializer, AttachedTaskSerializer

class LoginView(APIView):
    authentication_classes = []  # 不需要认证来访问登录视图
    permission_classes = [AllowAny]  # 允许所有用户访问登录视图
 
    def post(self, request, *args, **kwargs):
        username = request.data.get('username')
        password = request.data.get('password')
        
        # 使用authenticate函数来验证用户
        #user = authenticate(request, username=username, password=password)
        try:
            user = CustomUser.objects.get(username=username)
        except CustomUser.DoesNotExist:
            # 用户不存在
            return Response({"detail": "Invalid username or password."}, status=status.HTTP_400_BAD_REQUEST)
        
        print(str(username)+":"+str(password))
        # 如果用户不存在或密码不正确，authenticate将返回None
        if user is not None:
            # 如果用户是活跃的（对于自定义用户模型，你可能需要添加额外的检查）
            if user.is_active:
                # 使用login函数来设置会话信息
                login(request, user)
                return Response({"detail": "User logged in successfully."}, status=status.HTTP_200_OK)
            else:
                return Response({"detail": "User is inactive."}, status=status.HTTP_400_BAD_REQUEST)
        else:
            # 返回适当的错误信息
            return Response({"detail": "Invalid username or password."}, status=status.HTTP_400_BAD_REQUEST)
 

class CreateUserView(generics.CreateAPIView):
    queryset = CustomUser.objects.all()
    serializer_class = CustomUserSerializer

class ListUsersView(generics.ListAPIView):
    queryset = CustomUser.objects.all()
    serializer_class = CustomUserSerializer

class CreateTaskView(generics.CreateAPIView):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer
    permission_classes = [IsAuthenticated]

    @csrf_exempt
    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

class ListSubTasksByTaskIDView(generics.ListAPIView):
    serializer_class = SubTaskSerializer

    def get_queryset(self):
        task_id = self.kwargs['task_id']
        return SubTask.objects.filter(id=task_id)

class ListResponsibleSubTasksView(generics.ListAPIView):
    serializer_class = SubTaskSerializer

    def get_queryset(self):
        user_id = self.kwargs['user_id']
        user = get_object_or_404(CustomUser, id=user_id)
        return SubTask.objects.filter(responsible_user=user)

class CreateSubTaskView(generics.CreateAPIView):
    queryset = SubTask.objects.all()
    serializer_class = SubTaskSerializer
    #permission_classes = [IsAuthenticated]

    def perform_create(self, serializer):
        task_id = self.kwargs['task_id']
        username = self.kwargs['user_id']
        print("task_id:"+str(task_id))
        #task = get_object_or_404(Task, task_id=task_id)
        task = Task.objects.get(id=task_id)
        responsible_user = CustomUser.objects.get(id=username)
        serializer.save(task=task, created_by=self.request.user,responsible_user = responsible_user)

class CreateAttachedTaskView(generics.CreateAPIView):
    queryset = AttachedTask.objects.all()
    serializer_class = AttachedTaskSerializer
    #permission_classes = [IsAuthenticated]

    def perform_create(self, serializer):
        subtask_id = self.kwargs['subtask_id']
        subtask = get_object_or_404(SubTask, id=subtask_id)
        serializer.save(subtask=subtask, responsible_user=self.request.user)

class ListAttachedTasksByResponsibleUserView(generics.ListAPIView):
    serializer_class = AttachedTaskSerializer

    def get_queryset(self):
        user_id = self.kwargs['responsible_id']
        user = get_object_or_404(CustomUser, id=user_id)
        return AttachedTask.objects.filter(responsible_user=user)
		
class MessageViewSet(viewsets.ModelViewSet):
    queryset = Message.objects.all()
    serializer_class = MessageSerializer
    permission_classes = [IsAuthenticated]
 
    def perform_create(self, serializer):
        print(str("perform_create"))
        receiver_id = self.kwargs.get('receiver_id', None)
        receiver = CustomUser.objects.get(id=receiver_id)
        serializer.save(sender=self.request.user,receiver=receiver)
 
    def get_queryset(self):
        user = self.request.user
        queryset = super().get_queryset()
        print("get_queryset")		
        sender_id = self.request.query_params.get('sender', None)
        receiver_id = self.request.query_params.get('receiver', None)
        print(str(receiver_id)+":"+str(sender_id))		
        #sender = CustomUser.objects.get(id=sender_id)
        receiver = CustomUser.objects.get(id=receiver_id)
		        
        if receiver_id:
            return self.queryset.filter(receiver=receiver, receiver_id=receiver_id)
        elif sender_id:
            return self.queryset.filter(sender=user, sender_id=sender_id).count()  # Note: This should return a count for the endpoint returning the number of messages
        else:
            return self.queryset.filter(Q(sender=user) | Q(receiver=receiver))
 
    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        print(str("list"))
        if 'count' in request.query_params:  # Check if the request is to get the count of messages
            return Response({'count': queryset.count()}, status=status.HTTP_200_OK)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

class MessageViewShowSet(viewsets.ModelViewSet):
    queryset = Message.objects.all()
    serializer_class = MessageSerializer
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ['sender', 'receiver']  # 这里假设 sender 和 receiver 是外键字段
 
    # 如果 sender 和 receiver 是用户 ID 或其他字段，你可能需要自定义过滤逻辑
    def get_queryset(self):
        queryset = super().get_queryset()
        sender_id = self.request.query_params.get('sender', None)
        receiver_id = self.request.query_params.get('receiver', None)
 
        if sender_id is not None and receiver_id is not None:
            queryset = queryset.filter(sender_id=sender_id, receiver_id=receiver_id)
        elif sender_id is not None:
            queryset = queryset.filter(sender_id=sender_id)
        elif receiver_id is not None:
            queryset = queryset.filter(receiver_id=receiver_id)
 
        return queryset